from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.parsers import MultiPartParser, FormParser, FileUploadParser
from .serializers import FileLoaderSerializer
from .models import FileUploader
import pandas as pd
import json
from django.conf import settings
import time
import os


# Create your views here.
class FileUploaderViewSet(viewsets.ModelViewSet):
    queryset = FileUploader.objects.all()
    serializer_class = FileLoaderSerializer
    parser_classes = [MultiPartParser, FormParser]

    def perform_create(self, serializer):
        file_obj = self.request.data['file']
        serializer.validated_data['json_file'] = self.handle_uploaded_file(file_obj)
        serializer.validated_data['name'] = file_obj.name

        serializer.save()

    def handle_uploaded_file(self, f):
        df = pd.read_excel(f)
        item = {}
        item['manuellab_vers'] = [1, 6, 0]
        item['measures'] = {}
        for i in range(len(df['测量项'])):
            key = settings.MEASURES[df['测量项'][i]]
            value = round(df['测量值'][i] / 100, 3)
            item['measures'][key] = value
        time_now = int(time.time())
        json_file_name = str(time_now) + '.json'
        json_path = os.path.join(settings.MEDIA_ROOT, 'json', json_file_name)

        with open(json_path, 'w') as json_file:
            json_file.write(json.dumps(item))

        json_url = 'http://%s%sjson/%s' % (self.request.META['HTTP_HOST'], settings.MEDIA_URL, json_file_name)

        return json_url
